<template>
  <div class="padding-y-15 padding-x-30">
    <a-form
      :label-col="{ md: { span: 2 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 22 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-row :gutter="24">
        <a-col
          :md="6"
          :sm="12"
          :xs="10"
          style="
            height: calc(100vh - 160px);
            background-color: #fff;
            padding-left: 0;
            padding-right: 0;
          "
        >
          <div class="flex align-center padding-15" v-if="mShow">
            <a-avatar :size="40">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
            <a-input-search
              class="flex1 fs-12 margin-x-10"
              placeholder="会员手机（支持后4为）"
              v-model:value="memberVal"
              @search="searchMember"
            />
            <div
              class="add-btn flex align-center justify-center"
              @click="showEdit = true"
              >+</div
            >
          </div>
          <div class="flex align-center padding-15" v-if="!mShow">
            <a-avatar :size="40">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
            <div class="flex1 margin-left-15">
              <div>{{ memberInfo.name }}</div>
              <div>{{ memberInfo.nickname }}</div>
            </div>
            <img
              src="@/assets/out.png"
              style="width: 30px; height: 30px"
              @click="(mShow = true), (memberVal = ''), (memberInfo = {})"
            />
          </div>
          <div class="border">
            <div v-for="(item, index) in items" :key="index">
              <div class="flex align-center">
                <div class="flex1 left_title">
                  <template v-if="item.type == 1">首饰销售</template>
                  <template v-else-if="item.type == 3">新品换购</template>
                  <template v-else-if="item.type == 4">旧货换购</template>
                  <template v-else-if="item.type == 5">旧货回收</template>
                </div>
                <div class="flex1 left_title">
                  <template v-if="item.type == 1">实付金额（元）</template>
                  <template v-else-if="item.type == 3">抵扣金额（元）</template>
                  <template v-else-if="item.type == 4">抵扣金额（元）</template>
                  <template v-else-if="item.type == 5">回收金额（元）</template>
                </div>
                <div class="flex1 left_title"> 操作 </div>
              </div>
              <div
                class="flex align-center"
                :class="[current == index ? 'bg-f5f5f5' : '']"
              >
                <div class="flex1 left_con" @click="toDetail(item, index)">
                  <div>{{ item.bar_code }}</div>
                  <div>{{ item.name }}</div>
                </div>
                <div
                  class="flex1 left_con flex align-center justify-center"
                  @click="toDetail(item, index)"
                >
                  <template v-if="item.type == 1">{{
                    item.real_amount
                  }}</template>
                  <template v-else-if="item.type == 3">{{
                    item.discount_amount
                  }}</template>
                  <template v-else-if="item.type == 4">{{
                    item.discount_amount
                  }}</template>
                  <template v-else-if="item.type == 5">{{
                    item.discount_amount
                  }}</template>
                </div>
                <div class="flex1 left_con flex align-center justify-center"
                  ><close-circle-filled @click="delGoods(item)"
                /></div>
              </div>
            </div>
          </div>
        </a-col>
        <a-col :md="18" :sm="12" :xs="14" style="padding-left: 24px">
          <a-form
            :label-col="{ md: { span: 6 }, sm: { span: 10 }, xs: { span: 16 } }"
            :wrapper-col="{
              md: { span: 20 },
              sm: { span: 24 },
              xs: { span: 24 }
            }"
          >
            <a-row
              :gutter="24"
              style="background-color: #fff; padding: 15px 15px 0 15px"
            >
              <a-col :md="12" :sm="12" :xs="12">
                <a-form-item
                  label="主销导购"
                  :colon="false"
                  v-bind="validateInfos.main_salesman_id"
                >
                  <a-select
                    optionFilterProp="label"
                    :options="gouOptions"
                    allow-clear
                    placeholder="请选择"
                    v-model:value="payForm.main_salesman_id"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="12" :xs="12">
                <a-form-item label="辅销导购" :colon="false">
                  <a-select
                    optionFilterProp="label"
                    :options="gouOptions"
                    allow-clear
                    placeholder="请选择"
                    v-model:value="payForm.vice_salesman_id"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="12" :xs="12">
                <a-form-item label="消费动机" :colon="false">
                  <a-select
                    optionFilterProp="label"
                    :options="feeOptions"
                    allow-clear
                    placeholder="请选择"
                    v-model:value="payForm.consume_motive_code"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="12" :xs="12">
                <a-form-item
                  label="销售班组"
                  :colon="false"
                  v-bind="validateInfos.salesman_team_code"
                >
                  <a-radio-group v-model:value="payForm.salesman_team_code">
                    <a-radio
                      :value="item.value"
                      v-for="(item, index) in zuOptions"
                      :key="index"
                      >{{ item.label }}</a-radio
                    >
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="12" :xs="12">
                <a-form-item
                  label="客户来源"
                  :colon="false"
                  v-bind="validateInfos.member_from"
                >
                  <a-radio-group v-model:value="payForm.member_from">
                    <a-radio value="1">自然</a-radio>
                    <a-radio value="2">活动</a-radio>
                    <a-radio value="3">激活</a-radio>
                    <a-radio value="4">老带新</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="12" :xs="12">
                <a-form-item label="备注" :colon="false">
                  <a-select
                    style="width: 75%"
                    optionFilterProp="label"
                    allow-clear
                    placeholder="请选择"
                    :options="noteOptions"
                    v-model:value="payForm.note_id"
                  />
                  <img
                    src="@/assets/set.png"
                    style="
                      width: 30px;
                      height: 30px;
                      margin-left: 20px;
                      cursor: pointer;
                    "
                    @click="showNote = true"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row
              :gutter="24"
              style="background-color: #fff; margin-top: 15px"
            >
              <a-col :md="24" :sm="24" :xs="24" style="padding-left: 0">
                <div>
                  <a-radio-group
                    button-style="solid"
                    v-model:value="type"
                    @click="radioGroupChange(type)"
                  >
                    <a-radio-button value="1">首饰销售</a-radio-button>
                    <a-radio-button value="2">饰品销售</a-radio-button>
                    <a-radio-button value="3">新品换购</a-radio-button>
                    <a-radio-button value="4">旧货换购</a-radio-button>
                    <a-radio-button value="5">旧货回收</a-radio-button>
                    <a-radio-button value="6">赠品</a-radio-button>
                  </a-radio-group>
                </div>
              </a-col>
              <a-col :md="24" :sm="24" :xs="24" style="margin-top: 25px">
                <div class="flex align-center padding-bottom-15">
                  <div class="flex1 flex align-center">
                    <span class="fs-12">货品条码</span>
                    <a-input-search
                      placeholder="请输入"
                      style="
                        width: 260px;
                        margin-left: 15px;
                        margin-right: 15px;
                      "
                      enter-button="搜索"
                      v-model:value="searchVal"
                      @search="search"
                    />
                  </div>
                  <a-space v-if="type == 1 && typeShow">
                    <a-button type="primary" @click="save1()">确认</a-button>
                  </a-space>
                  <a-space v-else-if="type == 3">
                    <a-button type="primary" @click="save3()">确认</a-button>
                  </a-space>
                  <a-space v-else-if="type == 4">
                    <a-button @click="ShowLuHas41 = true">手工录入</a-button>
                    <a-button type="primary" @click="save4()">确认</a-button>
                  </a-space>
                  <a-space v-else-if="type == 5">
                    <a-button @click="ShowLuHas51 = true">手工录入</a-button>
                    <a-button type="primary" @click="save5()">确认</a-button>
                  </a-space>
                </div>
              </a-col>
              <a-col
                :md="24"
                :sm="24"
                :xs="24"
                style="height: calc(100vh - 465px); overflow-y: auto"
                v-if="type == 1 && typeShow"
              >
                <sale
                  ref="saleRef"
                  v-if="ShowSale"
                  :member_id="memberInfo.id"
                  @get_been_order="get_been_order"
                />
              </a-col>
              <a-col
                :md="24"
                :sm="24"
                :xs="24"
                style="
                  height: calc(100vh - 465px);
                  margin-top: 15px;
                  overflow-y: auto;
                "
                v-else-if="type == 3"
              >
                <new-to-buy
                  v-if="!ShowLuHas3"
                  :member_id="memberInfo.id"
                  @getBarCode3="getBarCode3"
                />
                <!-- 新品换购 手工录入 本司货品 按件  弹窗 -->
                <new-to-buy-lu-has
                  ref="newtobuyluhas"
                  v-if="ShowLuHas3"
                  :member_id="memberInfo.id"
                  :bar_code="new_to_buy_code"
                  @get_been_order="get_been_order"
                  @changeShow="changeShow"
                />
              </a-col>
              <a-col
                :md="24"
                :sm="24"
                :xs="24"
                style="
                  height: calc(100vh - 465px);
                  margin-top: 15px;
                  overflow-y: auto;
                "
                v-else-if="type == 4"
              >
                <old-to-buy
                  v-if="!ShowLuHas4"
                  :member_id="memberInfo.id"
                  @getBarCode4="getBarCode4"
                />
                <old-to-buy-detail
                  ref="oldtobuydetail"
                  v-if="ShowLuHas4"
                  :member_id="memberInfo.id"
                  :bar_code="old_to_buy_code"
                  @get_been_order="get_been_order"
                  @changeShow="changeShow"
                />
              </a-col>
              <a-col
                :md="24"
                :sm="24"
                :xs="24"
                style="
                  height: calc(100vh - 465px);
                  margin-top: 15px;
                  overflow-y: auto;
                "
                v-else-if="type == 5"
              >
                <recovery-to-buy
                  v-if="!ShowLuHas5"
                  :member_id="memberInfo.id"
                  @getBarCode5="getBarCode5"
                />
                <recovery-to-buy-detail
                  ref="recoverytobuydetail"
                  v-if="ShowLuHas5"
                  :member_id="memberInfo.id"
                  :bar_code="recovery_to_buy_code"
                  @get_been_order="get_been_order"
                  @changeShow="changeShow"
                />
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
    </a-form>
    <div class="ele-bottom-tool">
      <div class="ele-bottom-tool-actions">
        <a-form
          :label-col="{ md: { span: 6 }, sm: { span: 10 }, xs: { span: 16 } }"
          :wrapper-col="{
            md: { span: 20 },
            sm: { span: 24 },
            xs: { span: 24 }
          }"
        >
          <a-row>
            <a-col :md="6" :sm="6" :xs="6">
              <a-form-item
                label="销售日期"
                :colon="false"
                style="margin-bottom: 0"
                v-bind="validateInfos.sales_time"
              >
                <a-date-picker
                  style="width: 100%"
                  valueFormat="YYYY/MM/DD"
                  autocomplete="off"
                  placeholder="请选择日期"
                  v-model:value="payForm.sales_time"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="6" :xs="6">
              <a-form-item
                label="整单折扣"
                :colon="false"
                style="margin-bottom: 0"
              >
                <a-input
                  allow-clear
                  placeholder="请输入"
                  v-model:value="payForm.discount"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="6" :xs="6">
              <a-form-item
                label="整单抹零"
                :colon="false"
                style="margin-bottom: 0"
              >
                <a-input
                  allow-clear
                  placeholder="请输入"
                  v-model:value="payForm.small_change"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="6" :xs="6">
              <a-form-item
                label=""
                :colon="false"
                style="margin-bottom: 0; white-space: nowrap"
              >
                <span class="fw-bolder margin-right-15"
                  >实收金额： {{ payForm.pay_amount || 0 }}</span
                >
                <a-button type="primary" @click="toPay()">去收款</a-button>
                <a-button @click="guadan()">挂单</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <note-list v-if="showNote" v-model:visible="showNote" @getNote="getNote" />
    <!-- 新增/编辑弹窗 -->
    <select-member
      v-if="showMember"
      :memberVal="memberVal"
      v-model:visible="showMember"
      @getMember="getMember"
    />
    <!-- 新建会员 -->
    <user-edit
      v-if="showEdit"
      actionStatus="add"
      v-model:visible="showEdit"
      :memberVal="memberVal"
      @done="done"
    />
    <!-- 赠送积分弹窗 -->
    <send
      v-if="showSend"
      v-model:visible="showSend"
      :member_id="memberInfo.id"
      :order_sn="payForm.order_sn"
      @doSend="doSend"
      @clear_been_order="clear_been_order"
    />
    <!-- 旧货换购  手工录入 本司货品 按件  弹窗 -->
    <old-to-buy-lu-has
      v-if="ShowLuHas41"
      v-model:visible="ShowLuHas41"
      :member_id="memberInfo.id"
      :bar_code="old_to_buy_code"
      @get_been_order="get_been_order"
    />
    <!-- 旧货回收  手工录入 本司货品 按件  弹窗 -->
    <recovery-to-buy-lu-has
      v-if="ShowLuHas51"
      v-model:visible="ShowLuHas51"
      :member_id="memberInfo.id"
      :bar_code="recovery_to_buy_code"
      @get_been_order="get_been_order"
    />
    <!-- 收款 弹窗 -->
    <receiveMoney
      v-if="ShowReceive"
      v-model:visible="ShowReceive"
      :member_id="memberInfo.id"
      :money="payForm.pay_amount"
      :order_sn="payForm.order_sn"
      @get_been_order="get_been_order"
      @clear_been_order="clear_been_order"
    />
  </div>
</template>

<script setup>
  import {
    ref,
    unref,
    reactive,
    onMounted,
    watch,
    getCurrentInstance
  } from 'vue';
  import {
    UserOutlined,
    PlusSquareOutlined,
    CloseCircleFilled
  } from '@ant-design/icons-vue';
  import { Form, Modal, message } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import { reloadPageTab, finishPageTab } from '@/utils/page-tab-util';
  import noteList from './components/noteList.vue';
  import selectMember from './components/select-member.vue';
  import send from './components/send.vue';
  import receiveMoney from './components/pay.vue';
  import userEdit from '@/views/member/member/get_list/components/user-edit.vue';
  import sale from './components/sale/sale.vue';
  import newToBuy from './components/newtobuy/newToBuy.vue';
  import newToBuyLuHas from './components/newtobuy/newToBuyLuHas.vue';
  import oldToBuy from './components/oldtobuy/oldToBuy.vue';
  import oldToBuyDetail from './components/oldtobuy/oldToBuyDetail.vue';
  import oldToBuyLuHas from './components/oldtobuy/oldToBuyLuHas.vue';
  import oldToBuyLuHasEdit from './components/oldtobuy/oldToBuyLuHasEdit.vue';
  import recoveryToBuy from './components/recovery/recoveryToBuy.vue';
  import recoveryToBuyDetail from './components/recovery/recoveryToBuyDetail.vue';
  import recoveryToBuyLuHas from './components/recovery/recoveryToBuyLuHas.vue';
  import { setting_list } from '@/api/setting/cashier_setting';
  import {
    salesman_list,
    store_team,
    get_note_list,
    jewelry_order,
    been_order,
    del_been_order,
    go_pay,
    go_maker
  } from '@/api/order/order/jewelry_order';
  import { get_list } from '@/api/setting/sales_subject';
  import { goods_info } from '@/api/jewelry/goods_info';
  import { get_price } from '@/api/setting/tenant_price';
  import { add } from '@/api/member/get_list';
  import { pay } from '@/api/order/pay';
  import { detail } from '@/api/member/get_list';

  const useForm = Form.useForm;
  const { currentRoute, push } = useRouter();
  const { query } = unref(currentRoute);
  console.log('query', query);

  const items = ref([]);
  const type = ref('1');
  const typeShow = ref(false);
  const showNote = ref(false);
  const showMember = ref(false);

  const mShow = ref(true);
  const memberVal = ref(null);
  const gouOptions = ref([]);
  const feeOptions = ref([]);
  const signOptions = ref([]);
  const zuOptions = ref([]);
  const noteOptions = ref([]);
  const searchVal = ref(null);
  const info = ref({});
  const memberInfo = ref({});

  const showEdit = ref(false);
  const showSend = ref(false);
  const ShowReceive = ref(false);

  const current = ref(-1);
  //首饰销售
  const sale_code = ref(null);
  const ShowSale = ref(true);
  const saleRef = ref(null);
  //新品换购
  const new_to_buy_code = ref(null);
  const ShowLuHas3 = ref(false);
  const newtobuyluhas = ref(null);
  //旧货换购
  const old_to_buy_code = ref(null);
  const ShowLuHas4 = ref(false);
  const ShowLuHas41 = ref(false);
  const oldtobuydetail = ref(null);
  //旧货回收
  const recovery_to_buy_code = ref(null);
  const ShowLuHas5 = ref(false);
  const ShowLuHas51 = ref(false);
  const recoverytobuydetail = ref(null);
  //收银台设置
  const setting = ref({});

  const form = reactive({
    order_sn: '',
    member_id: '',
    goods_code: '',
    thumb: '',
    gold_weight: '', //净金重
    sales_gold_price: '', //销售金价
    sales_labor: '', //销售工费
    regular_discount: 100,
    coupon_id: '',
    points: '',
    points_deduction: '',
    small_change: 0, //抹零
    small_change2: 0, //整单折扣抹零
    small_change3: 0, //整单抹零
    real_discount: '',
    original_amount: '', //原售价
    real_amount: '', //实售价
    sales_tag_code: '',
    note: ''
  });
  const payForm = reactive({
    member_id: '',
    order_sn: '',
    main_salesman_id: null,
    vice_salesman_id: null,
    consume_motive_code: null,
    salesman_team_code: null,
    member_from: '',
    note_id: null,
    sales_time: '',
    discount: 0,
    small_change: 0,
    pay_amount: 0
  });
  /* 
	 净金重     form.gold_weight
	 销售金价   form.sales_gold_price
	 销售工费   form.sales_labor
	 抹零       form.small_change
	 积分抵扣金额 form.points_deduction
	 固定折扣    form.regular_discount
	*/
  watch(
    () => [payForm.discount, payForm.small_change],
    (newValue, oldValue) => {
      console.log('newValue===', newValue);
      js_fansuan_price1();
    }
  );

  const js_fansuan_price1 = async () => {
    //反算
    let total = 0;
    await items.value.forEach((item) => {
      if (item.type == 1) {
        total += Number(item.real_amount);
        item.small_change1 = item.small_change;
        item.small_change2 = 0; //反算整单折扣抹零
        item.small_change3 = 0; //反算整单抹零
      }
    });
    let reduce_total = total * (1 - Number(payForm.discount) / 100).toFixed(2);
    await items.value.forEach((item) => {
      if (item.type == 1) {
        if (payForm.discount) {
          item.real_amount2 = (
            (Number(item.real_amount) * Number(payForm.discount)) /
            100
          ).toFixed(2);
        } else {
          item.real_amount2 = Number(item.real_amount).toFixed(2);
          reduce_total = 0;
        }

        item.small_change2 = (
          (Number(item.real_amount) / Number(total)) *
          reduce_total
        ).toFixed(2);
        item.small_change1 = (
          Number(item.small_change1) + Number(item.small_change2)
        ).toFixed(2);
      }
      console.log('=-=-=-=-=-0000===', items.value);
    });
    await js_fansuan_price2();
  };
  const js_fansuan_price2 = async () => {
    //反算
    let total = 0;
    await items.value.forEach((item) => {
      if (item.type == 1) {
        total += Number(item.real_amount2);
        item.small_change1 = item.small_change;
        item.small_change3 = 0; //反算整单抹零
      }
    });
    await items.value.forEach((item) => {
      if (item.type == 1) {
        item.small_change3 = (
          (Number(item.real_amount2) / Number(total)) *
          Number(payForm.small_change)
        ).toFixed(2);
        item.small_change1 = (
          Number(item.small_change1) + Number(item.small_change3)
        ).toFixed(2);

        if (payForm.small_change) {
          item.real_amount2 = (
            Number(item.real_amount2) - Number(item.small_change3)
          ).toFixed(2);
        } else {
          /* if (payForm.discount) {
            item.real_amount2 = Number(item.real_amount2).toFixed(2);
          } else {
            item.real_amount2 = Number(item.original_amount).toFixed(2);
          } */
          item.real_amount2 = Number(item.real_amount2).toFixed(2);
        }
      }
    });

    if (type.value == 1) {
      ShowSale.value = true;
      // saleRef.value.getSmallChange(items.value[current.value]);
    }

    suan_price();
  };

  const suan_price = () => {
    /* //计算总价
    payForm.pay_amount = 0;
    items.value.forEach((item) => {
      if (item.type == 1 || item.type == 2) {
        payForm.pay_amount += Number(item.real_amount2);
      } else if (item.type == 3 || item.type == 4 || item.type == 5) {
        payForm.pay_amount -= Number(Math.abs(item.discount_amount));
      }
    });
    if (setting.value.small_change == 1) {
      //四舍五入
      payForm.pay_amount = payForm.pay_amount.toFixed(0) + '.00';
    } else if (setting.value.small_change == 2) {
      //只入不舍
      payForm.pay_amount = Math.floor(payForm.pay_amount) + '.00';
    } else if (setting.value.small_change == 3) {
      //只舍不入
      payForm.pay_amount = Math.ceil(payForm.pay_amount) + '.00';
    } */
    //计算总价
    payForm.pay_amount = 0;
    items.value.forEach((item) => {
      if (item.type == 1 || item.type == 2) {
        payForm.pay_amount += Number(item.real_amount2);
      } else if (item.type == 3 || item.type == 4 || item.type == 5) {
        payForm.pay_amount -= Number(Math.abs(item.discount_amount));
      }
    });
    if (setting.value.small_change == 1) {
      //四舍五入
      payForm.pay_amount = payForm.pay_amount.toFixed(0) + '.00';
    } else if (setting.value.small_change == 2) {
      //只入不舍
      payForm.pay_amount = Math.floor(payForm.pay_amount) + '.00';
    } else if (setting.value.small_change == 3) {
      //只舍不入
      payForm.pay_amount = Math.ceil(payForm.pay_amount) + '.00';
    }
  };

  const get_been_order = () => {
    been_order({
      member_id: form.member_id
    }).then((res) => {
      if (type.value == 1) {
        typeShow.value = false;
      }
      if (res) {
        if (res.member_id) {
          payForm.member_id = res.member_id;
        }
        if (res.order_sn) {
          payForm.order_sn = res.order_sn;
        }
        if (res.main_salesman_id) {
          payForm.main_salesman_id = res.main_salesman_id;
        }
        if (res.vice_salesman_id) {
          payForm.vice_salesman_id = res.vice_salesman_id;
        }
        if (res.consume_motive_code != 0) {
          payForm.consume_motive_code = res.consume_motive_code;
        }
        if (res.salesman_team_code) {
          payForm.salesman_team_code = res.salesman_team_code;
        }
        if (res.member_from) {
          payForm.member_from = res.member_from.toString();
        }
        if (res.note_id) {
          payForm.note_id = res.note_id;
        }
        if (res.sales_time) {
          payForm.sales_time = res.sales_time;
        }
        if (res.discount) {
          payForm.discount = Number(res.discount);
        }
        if (res.small_change) {
          payForm.small_change = Number(res.small_change);
        }
        if (res.pay_amount) {
          payForm.pay_amount = Number(res.pay_amount);
        }
        /* payForm.member_id = res.member_id || '';
        payForm.order_sn = res.order_sn;
        payForm.main_salesman_id = res.main_salesman_id
          ? res.main_salesman_id
          : null;
        payForm.vice_salesman_id = res.vice_salesman_id
          ? res.vice_salesman_id
          : null;
        payForm.consume_motive_code = Number(res.consume_motive_code)
          ? res.consume_motive_code
          : null;
        payForm.salesman_team_code = res.salesman_team_code;
        payForm.member_from = res.member_from.toString();
        payForm.note_id = res.note_id ? res.note_id : null;
        payForm.sales_time = res.sales_time;
        payForm.discount = res.discount;
        payForm.small_change = res.small_change;
        payForm.pay_amount = res.pay_amount; */

        items.value = [];
        items.value = res.items;
        items.value.forEach((item) => {
          item.real_amount2 = item.real_amount;
          item.small_change1 = res.small_change;
          item.small_change2 = 0; //反算整单折扣抹零
          item.small_change3 = 0; //反算整单抹零
        });
        if (items.value.length > 0) {
          payForm.order_sn = items.value[0].order_sn;
        }
        suan_price();
      }
    });
  };

  onMounted(() => {
    store_team().then((res) => {
      zuOptions.value = res.data;
    });
    salesman_list().then((res) => {
      gouOptions.value = res.data;
    });
    get_list({
      page: 1,
      page_size: 99999,
      filters: {
        type: 'motive'
      }
    }).then((res) => {
      res.list.forEach((item) => {
        feeOptions.value.push({
          label: item.name,
          value: item.code
        });
      });
    });
    get_list({
      page: 1,
      page_size: 99999,
      filters: {
        type: 'sales'
      }
    }).then((res) => {
      res.list.forEach((item) => {
        signOptions.value.push({
          label: item.name,
          value: item.code
        });
      });
    });
    getNote();

    if (query.member_id) {
      form.member_id = query.member_id;
      detail({
        id: query.member_id
      }).then((res) => {
        getMember(res);
      });
    }

    setting_list().then((res) => {
      setting.value = res.data;
    });
  });

  const getNote = () => {
    get_note_list({
      page: 1,
      page_size: 9999
    }).then((res) => {
      noteOptions.value = [];
      res.data.forEach((item) => {
        noteOptions.value.push({
          label: item.name,
          value: item.id
        });
      });
    });
  };

  const toPay = () => {
    console.log('payForm', type.value);
    if (items.value.length > 0) {
      payForm.order_sn = items.value[0].order_sn;
    }
    validate().then(() => {
      go_pay(payForm)
        .then((res) => {
          message.success(res.msg);
          /* payForm.discount = '';
          payForm.small_change = '';
          items.value = []; */
          if (type.value == 5) {
            ShowReceive.value = true;
          } else {
            showSend.value = true;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    });
  };
  const guadan = () => {
    Modal.confirm({
      title: '提示',
      content: '确认挂单？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        payForm.order_sn = query.order_sn;
        go_maker(payForm)
          .then((res) => {
            message.success(res.msg);
            reloadPageTab();
          })
          .catch((e) => {
            message.error(e);
          });
      }
    });
  };
  const save1 = () => {
    if (type.value == 1) {
      saleRef.value.getMemberId(memberInfo.value.id);
    }
    saleRef.value.save();
  };

  const save3 = () => {
    newtobuyluhas.value.save();
  };
  const save4 = () => {
    oldtobuydetail.value.save();
  };
  const save5 = () => {
    recoverytobuydetail.value.save();
  };
  const search = (val) => {
    if (!val) {
      return message.warning('请输入正确条形码');
    }
    if (type.value == 1) {
      typeShow.value = true;
      setTimeout(() => {
        saleRef.value.search(val);
      }, 50);
    }
  };
  const delGoods = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除?',
      maskClosable: false,
      onOk: () => {
        del_been_order({
          member_id: form.member_id,
          item_id: item.id
        })
          .then((res) => {
            get_been_order();
            message.success(res.msg);
          })
          .catch((e) => {
            message.error(e || e.message);
          });
      }
    });
  };
  const searchMember = (e) => {
    memberVal.value = e;
    showMember.value = true;
  };
  const getMember = (val) => {
    console.log('val===', val);
    memberInfo.value = val;
    form.member_id = val.id;
    payForm.member_id = val.id;
    memberVal.value = val.mobile;
    showMember.value = false;
    mShow.value = false;
    get_been_order();
  };
  const done = (form) => {
    add(form)
      .then((res) => {
        showEdit.value = false;
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e);
      });
  };
  //新品换购选择货品后获取的bar_code
  const getBarCode3 = (val) => {
    new_to_buy_code.value = val.bar_code;
    ShowLuHas3.value = true;
  };
  //旧货换购选择货品后获取的bar_code
  const getBarCode4 = (val) => {
    old_to_buy_code.value = val.bar_code;
    ShowLuHas4.value = true;
  };
  //旧货回收选择货品后获取的bar_code
  const getBarCode5 = (val) => {
    recovery_to_buy_code.value = val.bar_code;
    ShowLuHas5.value = true;
  };
  const doSend = () => {
    ShowReceive.value = true;
  };

  //切换销售类型
  const radioGroupChange = (e) => {
    setTimeout(() => {
      searchVal.value = '';
      if (type.value == 1) {
        typeShow.value = false;
      } else if (type.value == 3) {
        ShowLuHas3.value = false;
      } else if (type.value == 4) {
        ShowLuHas4.value = false;
      } else if (type.value == 5) {
        payForm.discount = 0;
        payForm.small_change = 0;
        ShowLuHas5.value = false;
      }
    }, 50);
  };
  const toDetail = (item, index) => {
    current.value = index;
    //payForm.main_salesman_id = item.main_salesman_id
    if (item.type == 1) {
      type.value = '1';
      typeShow.value = true;
      ShowSale.value = true;
      setTimeout(() => {
        saleRef.value.getDetail(item);
      }, 500);
    } else if (item.type == 3) {
      type.value = '3';
      ShowLuHas3.value = true;
      setTimeout(() => {
        newtobuyluhas.value.getDetail(item);
      }, 50);
    } else if (item.type == 4) {
      type.value = '4';
      setTimeout(() => {
        oldtobuydetail.value.getSmallChange(item);
      }, 50);
      ShowLuHas4.value = true;
    } else if (item.type == 5) {
      type.value = '5';
      setTimeout(() => {
        recoverytobuydetail.value.getSmallChange(item);
      }, 50);
      ShowLuHas5.value = true;
    }
  };

  const clear_been_order = () => {
    items.value = [];
    Object.keys(payForm).forEach((key) => {
      if (key != 'member_id') {
        payForm[key] = null;
      }
    });
  };

  const changeShow = () => {
    console.log('hahah', type.value.valuess);
    if (type.value == 3) {
      ShowLuHas3.value = false;
    }
    if (type.value == 4) {
      ShowLuHas4.value = false;
    }
    if (type.value == 5) {
      ShowLuHas5.value = false;
    }
  };

  // 表单验证规则
  const rules = reactive({
    main_salesman_id: [
      {
        required: true,
        message: '请选择主销导购',
        type: 'string',
        trigger: 'change'
      }
    ],
    salesman_team_code: [
      {
        required: true,
        message: '请选择销售班组',
        type: 'string',
        trigger: 'change'
      }
    ],
    member_from: [
      {
        required: true,
        message: '请选择客户来源',
        type: 'string',
        trigger: 'change'
      }
    ],
    sales_time: [
      {
        required: true,
        message: '请选择销售时间',
        type: 'string',
        trigger: 'change'
      }
    ]
  });
  const { validate, validateInfos } = useForm(form, rules);
</script>
